package tako.wisers.com.android.apis.preference;

import java.io.UnsupportedEncodingException;

import tako.wisers.com.android.apis.R;
import tako.wisers.com.android.apis.database.SQListManager;
import tako.wisers.com.android.apis.http.ConfLoadService;
import tako.wisers.com.android.apis.item.SettingItem;
import tako.wisers.com.android.apis.setting.SettingManager;
import tako.wisers.com.android.apis.util.Global;
import tako.wisers.com.android.apis.view.DialogManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;

public class DownLoadPreference extends Preference {
	protected int type;
	public static final String VER_PIX = "ver.";
	private Context mCtx;
	private String mTitle;
	private String mSummary;
	private DialogManager mDm;

	public DownLoadPreference(Context context,AttributeSet attrs) {
		super(context);
		init(context);
	}

	public DownLoadPreference(Context context) {
		super(context);
		init(context);
	}
	
	private void init(Context context) {
		mCtx = context;
		mDm = new DialogManager(mCtx);
	}
	
	@Override
	protected void onClick() {
		mDm.build(Global.READ_DIALOG) ;
		execute();
	}

	public void execute() {
		setTitle(null);
		setSummary(null);
		switch (type) {
		case Global.CONF_DOWNLOAD_TYPE:
			xmlExecute();
			break;

		default:
			break;
		}
	}

	private void xmlExecute() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					TelephonyManager tm = (TelephonyManager) mCtx
							.getSystemService(Context.TELEPHONY_SERVICE);
					String USER_AGENT = tm.getLine1Number();
					ConfLoadService loadService = new ConfLoadService(mCtx
							.getString(R.string.app_name), USER_AGENT);
					loadService.reloadConf(SQListManager.getInstance());
					SettingManager sm = SettingManager.getInstance();
					SettingItem setting = sm.get(Global.CONF_DOWNLOAD_TYPE);
					
					mTitle = setting.getVersion();
					mSummary = setting.getHost();
					Message msg = handler.obtainMessage();
					handler.sendMessage(msg);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}
	
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			setTitle(VER_PIX + mTitle);
			setSummary(mSummary);
			mDm.dismiss();
		}
	};
}
